package com.ay.weixin.fdc.boss.autoreply.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.autoreply.db.IbatisAutoReplyDao;
import com.ay.weixin.autoreply.db.IbatisAutoReplyNewsDao;
import com.ay.weixin.autoreply.domain.Message;
import com.ay.weixin.autoreply.domain.MsgNews;
import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;

public class KeyWordReply extends Event{

	private IbatisAutoReplyDao auto_reply_dao;
	private IbatisAutoReplyNewsDao auto_reply_news_dao;
	
	@Override
	public void init_property() throws Exception {
		auto_reply_dao=Container.get(IbatisAutoReplyDao.class);
		auto_reply_news_dao=Container.get(IbatisAutoReplyNewsDao.class);
	}

	@Override
	public String default_handling_path() {
		return "/keywords/*";
	}
	
	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		Customer customer=(Customer)el.getSessionAttr("customer");
		if(customer==null){
			el.response_to_root(CustomerLogin.login_path());
			return;
		}
		try {
			if(el.queryPathCheck(1,"")){
				keywords(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"detail")){
				detail(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"add")){
				add(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"update")){
				update(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"add_text")){
				add_text(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"update_text")){
				update_text(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"delete_text")){
				delete_text(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"add_first_news")){
				add_first_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"append_news")){
				append_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"update_news")){
				update_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"delete_all_news")){
				delete_all_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"delete_one_news")){
				delete_one_news(el,customer.getWxprojectID());
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("replysetting.msg.bind.db.failure")+":"+e.getMessage());
			keywords(el,customer.getWxprojectID());
			return;
		}
	}

	
	private void add(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		
		String msg=el.getAttr("msg",null);
		List<Message> nlist=null;
		
		nlist=auto_reply_dao.getKeyWordsList(wxproject_id);
		el.setAttr("nlist",nlist);
		el.template("/WEB-INF/template/boss/reply/keywords/add.vm");
	}
	
	private void detail(EventLoader el,long wxproject_id) throws IOException, ServletException{
		long id=0;
		if(!el.paramExists("id")){
			id=el.getAttr("id",0l);
		}else{
			id=el.getLong("id");
		}
		
		String msg=el.getAttr("msg",null);
		Message message=null;
		try {
			message=auto_reply_dao.getById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			msg=el.i18("replysetting.msg.bind.db.failure");
			el.setAttr("msg",msg);
			el.template("/WEB-INF/template/boss/reply/index.vm");
			return;
			
		}
		el.setAttr("reply_msg", message);
		if(message!=null){
			if(StringHelper.equals(message.getResponse_type(), "news")){
				List<MsgNews> nlist=null;
				try {
					nlist=auto_reply_news_dao.getNewsList(wxproject_id,message.getId());
				} catch (SQLException e) {
					e.printStackTrace();
					msg=el.i18("replysetting.msg.bind.db.failure");
					el.setAttr("msg",msg);
					el.template("/WEB-INF/template/boss/reply/index.vm");
					return;
				}
				el.setAttr("reply_news", nlist);
				
			}
		}
		List<Message> nlist=null;
		
		try {
			nlist=auto_reply_dao.getKeyWordsList(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			msg=el.i18("replysetting.msg.bind.db.failure")+":"+e.getMessage();
		}
		el.setAttr("nlist",nlist);
		el.template("/WEB-INF/template/boss/reply/keywords/detail.vm");
	}

	private void keywords(EventLoader el,long wxproject_id) throws IOException, ServletException{
		String msg=el.getAttr("msg",null);
		Map<Long,Message> nmap=null;
		
		try {
			nmap=auto_reply_dao.getKeyWords(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			msg=el.i18("replysetting.msg.bind.db.failure")+":"+e.getMessage();
		}
		
		if(nmap!=null){
			Iterator<Entry<Long,Message>> itr=nmap.entrySet().iterator();
			Entry<Long,Message> tr=null;
			for(;itr.hasNext();){
				tr=itr.next();
				if(tr.getValue().getParent_id()!=-1){
					tr.getValue().setParent(nmap.get(tr.getValue().getParent_id()));
				}
			}
		}
		
		
		el.setAttr("msg",msg);
		el.setAttr("nlist",nmap.values());
		el.template("/WEB-INF/template/boss/reply/keywords/index.vm");
	}
	
	
	private void add_first_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		
		String msg=null;
        //检查输入请求是否为multipart表单数据。
        boolean isMultipart = ServletFileUpload.isMultipartContent(el.request());
        if(!isMultipart){
        	add(el,wxproject_id);
        	return;
        }
        Map<String,String> params=new HashMap<String,String>();
        String file_name=UUID.randomUUID().toString()+".jpg";
        String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
        File savedFile=null;
        boolean file_uploaded=false;
        /**为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。**/
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
            File cache_dir=new File(el.getRealPath("/WEB-INF/lizar/file_pos_form_cache"));
            if(!cache_dir.exists())cache_dir.mkdirs();
            factory.setRepository(cache_dir);// 设置缓冲区目录
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");//解决文件乱码问题
            upload.setSizeMax(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);// 设置最大文件尺寸
            List<FileItem> items = upload.parseRequest(el.request());
            if(items==null||items.isEmpty()){
            	  msg=el.i18("replysetting.news.image.upload.nofile.found");
            	  el.setAttr("msg",msg);
            	  add(el,wxproject_id);
                  return;
            }
            Iterator<FileItem> itr = items.iterator();//所有的表单项
            while (itr.hasNext()){
                 FileItem item = (FileItem) itr.next();//循环获得每个表单项
                 if(item.isFormField()){
                	 params.put(item.getFieldName(), new String(item.get(),"utf-8"));
                	 continue;
                 }
                 String name = item.getName();//获得文件名 包括路径啊
                 if(name.toLowerCase().endsWith(".jpg")){
                     savedFile=new File(file_path);
                     if(!savedFile.getParentFile().exists()){
                    	 savedFile.getParentFile().mkdirs();
                     }
                     item.write(savedFile);
                     file_uploaded=true;
                     break;
                 }
            }
        } catch (Exception e) {
            msg=el.i18("replysetting.news.image.upload.failed");
            el.setAttr("msg", msg);
            e.printStackTrace();
            add(el,wxproject_id);
            return;
        }
		
        if(!file_uploaded){
        	 msg=el.i18("replysetting.news.image.upload.nofile.found");
        	 el.setAttr("msg", msg);
        	 add(el,wxproject_id);
             return;
        }
        String description=params.get("description");
        if(description==null)description="";
        String input=params.get("input");
		String title=params.get("title");
		
		String url=params.get("url");
		
		System.out.println(params.get("parent_id"));
		
		long parent_id=StringHelper.isLong(params.get("parent_id"))?Long.parseLong(params.get("parent_id")):-1;
		
		if(StringHelper.isNull(input)){
			msg=el.i18("replysetting.keywords.cannot.be.empty");
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		if(description.length()>Keys.getInt("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("replysetting.news.description.max.length.exceed"),Keys.getInt("auto_reply.news_msg_description_length"));
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		if(StringHelper.isNull(title)){
			msg=el.i18("menu.news.title.cannot.be.empty");
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("replysetting.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(url)){
			msg=el.i18("replysetting.news.url.cannot.be.empty");
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("replysetting.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getMatchedInput(wxproject_id,input);
		if(message!=null){
			msg=el.i18("replysetting.keywords.already.exists");
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}else{
			message =new Message();
			message.setEvent("input");
			message.setMsg_type("text");
			message.setInput(input);
			message.setResponse_type("news");
			message.setParent_id(parent_id);
			message.setWxproject_id(wxproject_id);
			auto_reply_dao.insert_with_parent_id(message);
			message=auto_reply_dao.getMatchedInput(wxproject_id,input);
		}
		
		MsgNews msg_news=new MsgNews();
		msg_news.setArticle_count(0);
		msg_news.setAuto_reply_id(message.getId());
		msg_news.setDescription(description);
		msg_news.setTitle(title);
		msg_news.setUrl(url);
		msg_news.setPos(auto_reply_news_dao.getMaxPosByAutoReplyId(wxproject_id,message.getId()));
		msg_news.setPic_url(ReplySetting.getRelatImagePath(el,wxproject_id, file_name));
		msg_news.setWxproject_id(wxproject_id);
		auto_reply_news_dao.insert(msg_news);
		
		if(msg==null){
			msg=el.i18("replysetting.news.add.success");
		}
		el.setAttr("msg", msg);
		el.setAttr("input", input);
		keywords(el,wxproject_id);
	}
	
	private void append_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		
		String msg=null;
        //检查输入请求是否为multipart表单数据。
        boolean isMultipart = ServletFileUpload.isMultipartContent(el.request());
        if(!isMultipart){
        	detail(el,wxproject_id);
        	return;
        }
        Map<String,String> params=new HashMap<String,String>();
        String file_name=UUID.randomUUID().toString()+".jpg";
        String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
        File savedFile=null;
        boolean file_uploaded=false;
        /**为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。**/
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
            File cache_dir=new File(el.getRealPath("/WEB-INF/lizar/file_pos_form_cache"));
            if(!cache_dir.exists())cache_dir.mkdirs();
            factory.setRepository(cache_dir);// 设置缓冲区目录
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");//解决文件乱码问题
            upload.setSizeMax(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);// 设置最大文件尺寸
            List<FileItem> items = upload.parseRequest(el.request());
            if(items==null||items.isEmpty()){
            	  msg=el.i18("replysetting.news.image.upload.nofile.found");
            	  el.setAttr("msg",msg);
            	  detail(el,wxproject_id);
                  return;
            }
            Iterator<FileItem> itr = items.iterator();//所有的表单项
            while (itr.hasNext()){
                 FileItem item = (FileItem) itr.next();//循环获得每个表单项
                 if(item.isFormField()){
                	 params.put(item.getFieldName(), new String(item.get(),"utf-8"));
                	 continue;
                 }
                 String name = item.getName();//获得文件名 包括路径啊
                 if(name.toLowerCase().endsWith(".jpg")){
                     savedFile=new File(file_path);
                     if(!savedFile.getParentFile().exists()){
                    	 savedFile.getParentFile().mkdirs();
                     }
                     item.write(savedFile);
                     file_uploaded=true;
                     break;
                 }
            }
        } catch (Exception e) {
            msg=el.i18("replysetting.news.image.upload.failed");
            el.setAttr("msg", msg);
            e.printStackTrace();
            detail(el,wxproject_id);
            return;
        }
		
        if(!file_uploaded){
        	 msg=el.i18("replysetting.news.image.upload.nofile.found");
        	 el.setAttr("msg", msg);
        	 detail(el,wxproject_id);
             return;
        }
        String description=params.get("description");
        if(description==null)description="";
		String title=params.get("title");
		
		String url=params.get("url");
		
		long id=StringHelper.isLong(params.get("id"))?Long.parseLong(params.get("id")):-1;
		
		if(description.length()>Keys.getInt("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("replysetting.news.description.max.length.exceed"),Keys.getInt("auto_reply.news_msg_description_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		if(StringHelper.isNull(title)){
			msg=el.i18("menu.news.title.cannot.be.empty");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("replysetting.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(url)){
			msg=el.i18("replysetting.news.url.cannot.be.empty");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("replysetting.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getById(id);
		
		if(message==null){
			msg=el.i18("replysetting.keywords.not.exists");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		int size=auto_reply_news_dao.size_by_id(wxproject_id,message.getId());
		if(size>=Keys.getInt("auto_reply.one_msg_max_news")){
			 msg=String.format(el.i18("replysetting.news.max.news.number.exceed"),Keys.getInt("auto_reply.one_msg_max_news"));
			 el.setAttr("msg", msg);
			 detail(el,wxproject_id);
             return;
		}
		if(!StringHelper.equals(message.getResponse_type(), "news")){
			auto_reply_dao.update_response_type(message.getResponse_type(),message.getId());
		}
		
		MsgNews msg_news=new MsgNews();
		msg_news.setArticle_count(0);
		msg_news.setAuto_reply_id(message.getId());
		msg_news.setDescription(description);
		msg_news.setTitle(title);
		msg_news.setUrl(url);
		msg_news.setPos(auto_reply_news_dao.getMaxPosByAutoReplyId(wxproject_id,message.getId()));
		msg_news.setPic_url(ReplySetting.getRelatImagePath(el,wxproject_id, file_name));
		msg_news.setWxproject_id(wxproject_id);
		auto_reply_news_dao.insert(msg_news);
		
		if(msg==null){
			msg=el.i18("replysetting.news.add.success");
		}
		el.setAttr("msg", msg);
		el.setAttr("id", id);
		detail(el,wxproject_id);
	}
	
	private void delete_all_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long news_id=el.getLong("id");
		String msg=null;
		
		Message message =auto_reply_dao.getById(news_id);
		if(message==null){
			msg=el.i18("replysetting.news.message.not.exist");
			el.setAttr("msg", msg);
			keywords(el,wxproject_id);
			return;
		}
		
		if(auto_reply_dao.hasChildren(news_id)){
			msg=el.i18("replysetting.keywords.haschildren");
			el.setAttr("msg", msg);
			keywords(el,wxproject_id);
			return;
		}
		
		List<MsgNews> nlist=auto_reply_news_dao.getNewsList(wxproject_id,news_id);
		
		if(nlist!=null){
			Iterator<MsgNews> itr=nlist.iterator();
			MsgNews news=null;
			for(;itr.hasNext();){
				news=itr.next();
				String pic_url=news.getPic_url();
				File f=new File(el.getRealPath(pic_url));
				auto_reply_news_dao.delete_by_id(news.getId());
				f.delete();
			}
		}
		
		auto_reply_dao.delete_by_id(news_id);
		
		msg=el.i18("replysetting.news.message.delete.success");
		el.setAttr("msg", msg);
		
		keywords(el,wxproject_id);
	}
	
	private void delete_one_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long id=el.getLong("id");
		long news_id=el.getLong("news_id");
		String msg=null;
		Message message =auto_reply_dao.getById(id);
		if(message==null){
			msg=el.i18("replysetting.news.message.not.exist");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(auto_reply_dao.hasChildren(id)){
			msg=el.i18("replysetting.keywords.haschildren");
			el.setAttr("msg", msg);
			keywords(el,wxproject_id);
			return;
		}
		
		MsgNews news=auto_reply_news_dao.getById(news_id);
		
		if(news==null){
			msg=el.i18("replysetting.news.message.not.exist");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		auto_reply_news_dao.delete_by_id(news_id);
		
		String pic_url=news.getPic_url();
		File f=new File(el.getRealPath(pic_url));
		auto_reply_news_dao.delete_by_id(news.getId());
		f.delete();
		
		int size=auto_reply_news_dao.size_by_id(wxproject_id,news.getAuto_reply_id());
		
		msg=el.i18("replysetting.news.message.delete.success");
		
		if(size==0){
			auto_reply_dao.delete_by_id(id);
			keywords(el,wxproject_id);
			
		}else{
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
		}
	}
	
	private void update_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long news_id=el.getLong("news_id");
		String description=el.getStr("description");
		String title=el.getStr("title");
		String url=el.getStr("url");
		int pos=el.getInt("pos");
		String msg=null;
		
		
		if(description.length()>Keys.getInt("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("replysetting.news.description.max.length.exceed"),Keys.getInt("auto_reply.news_msg_description_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("replysetting.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("replysetting.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		MsgNews msg_news=auto_reply_news_dao.getById(news_id);
		if(msg_news==null){
			 msg=el.i18("replysetting.news.message.not.exist");
			 el.setAttr("msg", msg);
			 detail(el,wxproject_id);
			return;
		}
		
		MsgNews message=new MsgNews();
		message.setId(news_id);
		message.setDescription(description);
		message.setTitle(title);
		message.setPos(pos);
		message.setUrl(url);
		message.setWxproject_id(wxproject_id);
		auto_reply_news_dao.update(message);
		
		if(msg==null){
			msg=el.i18("replysetting.news.update.success");
		}
		el.setAttr("msg", msg);
		detail(el,wxproject_id);
	}
	
	

	
	private void add_text(EventLoader el,long wxproject_id) throws IOException, SQLException, ServletException{
		String input=el.getStr("input");
		long parent_id=el.getLong("parent_id",-1);
		if(StringHelper.isNull(input)){
			add(el,wxproject_id);
			return;
		}
		
		String content=el.getStr("content");
		String msg=null;
		if(StringHelper.isNull(content)){
			msg=el.i18("replysetting.text.content.cannot.be.empty");
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		if(content.length()>Keys.getInt("auto_reply.text_msg_conetnt_length")){
			msg=String.format(el.i18("replysetting.text.content.max.length.excceed"),Keys.getInt("auto_reply.text_msg_conetnt_length"));
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getMatchedInput(wxproject_id,input);
		if(message !=null){
			msg=el.i18("replysetting.text.msg.only.need.one");
			el.setAttr("msg", msg);
			add(el,wxproject_id);
			return;
		}
		message=new Message();
		message.setEvent("input");
		message.setContent(content);
		message.setInput(input);
		message.setMsg_type("text");
		message.setParent_id(parent_id);
		message.setResponse_type("text");
		message.setWxproject_id(wxproject_id);
		auto_reply_dao.insert_with_parent_id(message);
		if(msg==null){
			msg=el.i18("replysetting.msg.add.success");
		}
		el.setAttr("msg", msg);
		keywords(el,wxproject_id);
	}
	
	private void update_text(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		long id=el.getLong("id");
		long parent_id=el.getLong("parent_id",-1);
		String msg=null;
		
		String content=el.getStr("content");
		
		if(StringHelper.isNull(content)){
			msg=el.i18("replysetting.text.content.cannot.be.empty");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(content.length()>Keys.getInt("auto_reply.text_msg_conetnt_length")){
			msg=String.format(el.i18("replysetting.text.content.max.length.excceed"),Keys.getInt("auto_reply.text_msg_conetnt_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getById(id);
		if(message ==null){
			msg=el.i18("replysetting.text.msg.not.exist");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		message.setContent(content);
		message.setResponse_type("text");
		message.setParent_id(parent_id);
		message.setWxproject_id(wxproject_id);
		auto_reply_dao.update_text(message);
		if(msg==null){
			msg=el.i18("replysetting.msg.update.success");
		}
		el.setAttr("msg", msg);
		detail(el,wxproject_id);
		
	}
	
	private void update(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		System.out.println("1");
		long id=el.getLong("id");
		long parent_id=el.getLong("parent_id",-1);
		String msg=null;
		
		String input=el.getStr("input");
		
		if(StringHelper.isNull(input)){
			msg=el.i18("replysetting.keywords.cannot.be.empty");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getById(id);
		if(message ==null){
			msg=el.i18("replysetting.text.msg.not.exist");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		System.out.println("id:"+id+" parent_id:"+parent_id);
		System.out.println(message.getParent_id()+":"+parent_id);
		System.out.println(message.getInput()+":"+input);
		
		if(id==parent_id||(message.getParent_id()==parent_id&&StringHelper.equals(message.getInput(), input))){
			detail(el,wxproject_id);
			return;
		}
		System.out.println("3");
		if(!StringHelper.equals(input, message.getInput())&&auto_reply_dao.getMatchedInput(wxproject_id,input)!=null){
			msg=el.i18("replysetting.keywords.already.exists");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(parent_id!=-1&&auto_reply_dao.getById(parent_id)==null){
			msg=el.i18("replysetting.keywords.parent.not.exist");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		System.out.println("4");
		message.setInput(input);
		message.setParent_id(parent_id);
		message.setId(id);
		message.setWxproject_id(wxproject_id);
		System.out.println("parent_id1:"+parent_id);
		auto_reply_dao.update_keyword(message);
		if(msg==null){
			msg=el.i18("replysetting.keywords.update.success");
		}
		el.setAttr("msg", msg);
		detail(el,wxproject_id);
		
	}
	
	private void delete_text(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long id=el.getLong("id");
		
		String msg=null;
		
		Message message=auto_reply_dao.getById(id);

		if(message==null){
			msg=el.i18("replysetting.msg.delete.not.exists");
			el.setAttr("msg", msg);
			keywords(el,wxproject_id);
			return;
		}
		
		if(auto_reply_dao.hasChildren(id)){
			msg=el.i18("replysetting.keywords.haschildren");
			el.setAttr("msg", msg);
			keywords(el,wxproject_id);
			return;
		}
		
		if(StringHelper.equals(message.getResponse_type(), "news")){
			auto_reply_news_dao.delete_by_id(message.getId());
		}
		
		auto_reply_dao.delete_by_id(id);
		if(msg==null){
			msg=el.i18("replysetting.msg.delete.success");
		}
		el.setAttr("msg", msg);
		keywords(el,wxproject_id);
	}
}
